package com.msp.dao.common;

import java.util.List;
import java.util.Map;
import java.util.Set;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class BaseDao<T> {
	@Autowired
	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}
	
	@SuppressWarnings("unchecked")
	protected List<T> getOjects(Class<T> classz) {
		Session session = sessionFactory.getCurrentSession();
		List<T> list = session.createCriteria(classz).list();
		return list;
	}
	
	protected Integer insertObject(T obj) {
		Session session = sessionFactory.getCurrentSession();
		return (Integer) session.save(obj);
	}
	
	@SuppressWarnings("unchecked")
	protected T getObjectById(Class<T> classz, Integer id) {
		Session session = sessionFactory.getCurrentSession();
		return (T)session.byId(classz).load(id);
	}
	
	@SuppressWarnings("unchecked")
	protected List<T> getObjectsByParam(Class<T> classz, Map<String, Object> params) {
		Session session = sessionFactory.getCurrentSession();
		Criteria criteria = session.createCriteria(classz);
		Set<String> keys = params.keySet();
		for (String key : keys) {
			criteria.add(Restrictions.eq(key, params.get(key)));
		}
		return (List<T>)criteria.list();
	}
	
	protected void delete(T obj) {
		Session session = sessionFactory.getCurrentSession();
		session.delete(obj);
	}
	
	protected void update(T obj) {
		Session session = sessionFactory.getCurrentSession();
		session.update(obj);
	}
}
